package com.cskaoyan.mall.order.mq;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cskaoyan.mall.mq.constant.MqTopicConst;
import com.cskaoyan.mall.order.mapper.OrderInfoMapper;
import com.cskaoyan.mall.order.model.OrderInfo;
import com.cskaoyan.mall.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

@Component
@Slf4j
public class DelayOrderTopicConsumer {
    @Value("${rocketmq.namesrv.addr}")
    String namesrvAddr;

    @Value("${rocketmq.producer.group}")
    String producerGroup;

    @Autowired
    OrderService orderService;


    @PostConstruct
    public void delayOrderTopicConsumer() throws MQClientException {
//        DefaultMQPushConsumer defaultMQPushConsumer = new DefaultMQPushConsumer(producerGroup);
        DefaultMQPushConsumer defaultMQPushConsumer = new DefaultMQPushConsumer("delay-order-group");
        defaultMQPushConsumer.setNamesrvAddr(namesrvAddr);
        defaultMQPushConsumer.subscribe(MqTopicConst.DELAY_ORDER_TOPIC,"*");
        defaultMQPushConsumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msg, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                try{
                    log.info(MqTopicConst.DELAY_ORDER_TOPIC+"接收到延迟消息");
                    //判断是否依然是未付款
                    MessageExt message = msg.get(0);
                    byte[] body = message.getBody();
                    String orderIdStr = new String(body, StandardCharsets.UTF_8);
                    Long orderId= Long.valueOf(orderIdStr);
                    //查数据库
                    orderService.execExpiredOrder(orderId);

                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }catch (Exception e){
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
            }
        });

        defaultMQPushConsumer.start();
    }
}
